# -*- coding: utf-8 -*-
"""
    :author: Grey Li (李辉)
    :url: http://greyli.com
    :copyright: © 2018 Grey Li <withlihui@gmail.com>
    :license: MIT, see LICENSE for more details.
"""
from flask import jsonify, request, current_app, url_for, g
from flask_restful import Resource, reqparse
from agv_back.apis.v1 import api_v1, api
from agv_back.apis.v1.auth import auth_required, generate_token
from agv_back.apis.v1.errors import api_abort, ValidationError
from agv_back.extensions import db
from agv_back.models.User import User


class IndexAPI(Resource):
    def get(self):
        return jsonify({
            "api_version": "1.0",
            "api_base_url": "http://10.178.61.24.com/api/v1",
            "current_user_url": "http://10.178.61.24.com/api/v1/user",
            "authentication_url": "http://example.com/api/v1/token",
            "item_url": "http://example.com/api/v1/items/{item_id }",
            "current_user_items_url": "http://example.com/api/v1/user/items{?page,per_page}",
            "current_user_active_items_url": "http://example.com/api/v1/user/items/active{?page,per_page}",
            "current_user_completed_items_url": "http://example.com/api/v1/user/items/completed{?page,per_page}",
        })


class RigisterAPI(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username', type=str, help='username to login', required=True)
        parser.add_argument('password', type=str, help='password to login', required=True)
        parser.add_argument('is_admin', type=bool, help='admin or client', default=False)
        args = parser.parse_args(strict=True)
        username = args['username']
        password = args['password']
        is_admin = args['is_admin']
        user_is_exit = User.query.filter_by(username=username).first()
        if user_is_exit is not None:
            return api_abort(code=400, message=f'The User {username} has exit,please set another username')
        user = User(username=username, is_admin=is_admin)
        user.set_password(password)
        db.session.add(user)
        db.session.commit()
        user_info = dict(username=username,
                         password=password,
                         is_admin=is_admin)
        return jsonify(user_info=user_info,
                       code=200, message="register success!")

class AuthLogoutAPI(Resource):
    method_decorators = [auth_required]
    def post(self):
        #todo:we can record the user's last time to login
        return jsonify(code=200,message="log out success!")

class AuthTokenAPI(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('username', type=str, help='need username to login', required=True)
        parser.add_argument('password', type=str, help='need password to login', required=True)
        args = parser.parse_args(strict=True)
        username = args['username']
        password = args['password']

        user = User.query.filter_by(username=username).first()
        if user is None or not user.validate_password(password):
            return api_abort(code=400, message='Either the username or password was invalid.')

        token, expiration = generate_token(user)

        response = jsonify({
            'data':{
                'token': token,
                'token_type': 'Bearer',
                'expires_in': expiration,
            },
            'code':200,
            'message':'login success!'
        })
        response.headers['Cache-Control'] = 'no-store'
        response.headers['Pragma'] = 'no-cache'
        return response


class UserAPI(Resource):
    method_decorators = [auth_required]
    def get(self):
        # return jsonify(user_schema(g.current_user))
        # todo:return the user info
        data = dict(name="dl",avatar="")
        return jsonify(data=data,code=200,message="get user info success!")


api.add_resource(IndexAPI, '/')
api.add_resource(UserAPI, '/user')
api.add_resource(RigisterAPI, '/oauth/register')
api.add_resource(AuthTokenAPI, '/oauth/token')
api.add_resource(AuthLogoutAPI, '/oauth/logout')

# api_v1.add_url_rule('/', view_func=IndexAPI.as_view('index'), methods=['GET'])
# api_v1.add_url_rule('/oauth/token', view_func=AuthTokenAPI.as_view('token'), methods=['POST'])
# api_v1.add_url_rule('/user', view_func=UserAPI.as_view('user'), methods=['GET'])
